package com.lecoboy.highconcurrency.concurrent_tools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量测试类
 * 线程使用acquire()方法获取一个许可证，使用完之后调用release()方法归还许可证
 * 还可以用tryAcquire()方法尝试获取许可证
 */
public class SemaphoreTest {
    private static final int THREAD_COUNT = 30;
    private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
    //10表示允许10个线程获取许可证，也就是最大并发数10
    private static Semaphore s = new Semaphore(10);

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        s.acquire();
                        //延迟为了视觉显示每次10个并发
                        TimeUnit.SECONDS.sleep(2);
                        System.out.println("save data");
                        s.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }

}
